﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;

namespace Twc.Deployment.Client.Logic
{
    public class ProcessService : IDisposable
    {
        Process _process;
        ProcessStartInfo _processInfo;
        bool _disposed;

        public ProcessService()
        {
            _processInfo = new ProcessStartInfo();
            _processInfo.FileName = @"C:\windows\system32\cmd.exe";
            _processInfo.UseShellExecute = false;
            _processInfo.RedirectStandardInput = true;
            _processInfo.RedirectStandardOutput = true;
            _processInfo.CreateNoWindow = true;

            _disposed = false;
        }

        public void WriteCommand(string command)
        {
            if (_process == null && !this._disposed)
                _process = Process.Start(_processInfo);
            if (!this._disposed)
                _process.StandardInput.WriteLine(command);
        }

        public void WriteExitCommand()
        {
            WriteCommand("exit");
        }

        public void Wait(int milliseconds)
        {
            Thread.Sleep(milliseconds);
        }

        public void WriteCommandAndWait(string command, int milliseconds)
        {
            WriteCommand(command);
            Wait(milliseconds);
        }

        public string ReadOutput()
        {
            string output = null;
            if (!this._disposed)
            {
                using (BackgroundWorker worker = new BackgroundWorker())
                {
                    worker.DoWork += (sender, e) => { _process.WaitForExit(); };
                    worker.RunWorkerCompleted += (sender, e) => output = _process.StandardOutput.ReadToEnd();
                    worker.RunWorkerAsync();

                    while (output == null)
                    {
                        Thread.Sleep(6000);
                        if (output == null)
                            WriteExitCommand();
                    }
                }
            }

            return output;
        }

        #region IDisposable Members

        public void Dispose()
        {
            _disposed = true;
            if (_process != null)
                _process.Dispose();
        }

        #endregion
    }
}
